﻿define(function (require, exports, module) {

    var $ = require('jquery');
    var ma = require('mustache');
    var url = require('querystring');

    require('jpager')($);

    //window.$ = $;
    //window.jQuery = $;

    var tmpl = '{{#posts}}\
     <tr>\
		<td><a href="{{Path}}" target="_blank">{{Title}}</a></td>\
		<td>{{Author}}</td>\
		<td>{{Date}}</td>\
		<td>{{Version}}</td>\
		<td><a href="/_sys/admin/page?path={{Path}}" target="_blank">编辑</a>\
            <a href="#update_url" data-url="{{Path}}">修改URL</a>\
        </td>\
    </tr>{{/posts}}';

    var loading = '<tr><td colspan="6">加载中，请稍后...</td></tr>';
    var empty = '<tr><td colspan="6">没有任何内容</td></tr>';

    var postsTbl = $("#posts").find("tbody")

    var dateFormater = function (date, format) {
        var o = {
            "M+": date.getMonth() + 1, //month 
            "d+": date.getDate(),    //day 
            "h+": date.getHours(),   //hour 
            "m+": date.getMinutes(), //minute 
            "s+": date.getSeconds(), //second 
            "q+": Math.floor((date.getMonth() + 3) / 3),  //quarter 
            "S": date.getMilliseconds() //millisecond 
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
              RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }

    var renderPosts = function (posts) {
        var len = posts.length;
        for (var i = 0; i < len; i++) {
            var date = new Date(posts[i].Date);
            posts[i].Date = dateFormater(date, "yyyy-MM-dd hh:mm:ss");
        }

        var obj = {};
        obj.posts = posts;
        var html = ma.to_html(tmpl, obj);
        postsTbl.html(html);
    }

    var order = "-Id";
    var limit = 20;
    var startOffset = 0;

    var loadPosts = function (_offset, _limit, _order) {

        _offset = _offset || 0;
        _limit = _limit || limit;
        _order = _order || order;
        order = _order;

        postsTbl.html(loading);

        $.ajax({
            url: "/_sys/admin/pages/get",
            data: { offset: _offset, limit: _limit, order: _order },
            dataType: "json",
            cache: false,
            success: function (json) {
                if (json) {
                    renderPosts(json);
                } else {
                    postsTbl.html(empty);
                }
                bindUpdateUrl();
            }
        });
    }

    var bindUpdateUrl = function () {
        postsTbl.find("a[href='#update_url']").each(function (i) {
            var a = $(this);
            a.click(function () {
                var path = a.attr("data-url");
                if (npath = window.prompt("请输入新URL地址：", path)) {
                    if (npath != path) {
                        $.ajax({
                            url: "/_sys/admin/paths/set",
                            data: { path: path, npath: npath },
                            dataType: "json",
                            cache: false,
                            success: function (json) {
                                if (json.Path) {
                                    a.attr("data-url", npath);
                                    alert("修改成功。");
                                }
                                else {
                                    console.log(json);
                                    alert("修改失败");
                                }
                            },
                            type: "POST"
                        });
                    }
                }
            });
        });

    }

    exports.init = function () {
        var href = document.location.href;
        var q = url.parse(href.substring(href.indexOf("#") + 1), sep = '&', eq = '=')
        if (q.offset) {
            offset = parseInt(q.offset);
        }
        if (q.show && q.show == "posts") {
            order = "-Id";
        }

        $.ajax({
            url: "/_sys/admin/paths/max",
            dataType: "json",
            cache: false,
            success: function (json) {
                $(".page").jpager({
                    totalItems: json.Id - 1,
                    limit: limit,
                    showFirstLast: true,
                    pageGo: function (a, b, c) {
                        loadPosts(b, c);
                    }
                });
                loadPosts(startOffset, limit);
            }
        });

        var linkPages = $("#showPages");
        var linkLatests = $("#showLatest");
        var linkUsers = $("#showUsers");

        linkPages.click(function () {
            loadPosts(startOffset, limit, "-Id");
        });
        linkLatests.click(function () {
            loadPosts(startOffset, limit, "-Date");
        });

        var toc = $("#toc").find("li");
        toc.each(function () {
            var a = $(this);
            a.click(function () {
                toc.removeClass("toc-active");
                a.addClass("toc-active");
            });
        });
    };
});